﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace mainAppView
{
    

 public partial class mainView : Form
 {

     private const int WS_EX_NOACTIVATE = 0x08000000;

     protected override CreateParams CreateParams
     {
         get
         {
             CreateParams createParams = base.CreateParams;
             createParams.ExStyle = createParams.ExStyle & WS_EX_NOACTIVATE;
             return createParams;
         }
     }
     private const int WM_MOUSEACTIVATE = 0x0021;
     private const int MA_NOACTIVATE = 0x0003;
     protected override void WndProc(ref Message m)
     {
         //If we're being activated because the mouse clicked on us...
         if (m.Msg == WM_MOUSEACTIVATE)
         {
             //Then refuse to be activated, but allow the click event to pass through (don't use MA_NOACTIVATEEAT)
             m.Result = (IntPtr)MA_NOACTIVATE;
         }
         else
         {
             base.WndProc(ref m);
         }
     }


     #region custom cursor lib imports
     //code for custom cursors begins----
     [DllImport("user32.dll")]
     [return: MarshalAs(UnmanagedType.Bool)]
     public static extern bool GetIconInfo(IntPtr hIcon, ref IconInfo pIconInfo);

     [DllImport("user32.dll")]
     public static extern IntPtr CreateIconIndirect(ref IconInfo icon);

     public static Cursor CreateCursor(Bitmap bmp, int xHotSpot, int yHotSpot)
     {
         IntPtr ptr = bmp.GetHicon();
         IconInfo tmp = new IconInfo();
         GetIconInfo(ptr, ref tmp);
         tmp.xHotspot = xHotSpot;
         tmp.yHotspot = yHotSpot;
         tmp.fIcon = false;
         ptr = CreateIconIndirect(ref tmp);
         return new Cursor(ptr);
     }
     //code for custom cursors ends------
     #endregion

        FormState formState = new FormState();   //allow set to fullscreen
        disablekeys disable = new disablekeys(); //low level hook to cancel key combos

        private bool isMouseHeld = false;
        private Button currentButton;
        private int num = 0;
        private Point lastMouseDownLocation;
        private storyForm story;

        public mainView()
        {
            InitializeComponent();
        }

        private void mainView_Load(object sender, EventArgs e)
        {
          formState.Maximize(this);//fullscreen

            /*  begin initialisation of keyboard grabbing  */
            ProcessModule objCurrentModule = Process.GetCurrentProcess().MainModule;
            disable.objKeyboardProcess = new disablekeys.LowLevelKeyboardProc(disable.captureKey);
            disable.ptrHook = disablekeys.SetWindowsHookEx(13, disable.objKeyboardProcess, disablekeys.GetModuleHandle(objCurrentModule.ModuleName), 0);
            /*  end  */
            this.panel1.Size = new System.Drawing.Size(this.Size.Width/6, this.Size.Height/2 + 100);
            this.panel1.Location = new System.Drawing.Point(3,this.Size.Height/4 + 90);

            mainAppView.Keyboard.TouchScreenKeyboard._InstanceObject.Closing += new CancelEventHandler(mainAppView.Keyboard.TouchScreenKeyboard._InstanceObject_Closing);
            mainAppView.Keyboard.TouchScreenKeyboard._InstanceObject.Closed += new EventHandler(mainAppView.Keyboard.TouchScreenKeyboard._InstanceObject_Closed);
            mainAppView.Keyboard.TouchScreenKeyboard._InstanceObject.LostFocus += new System.Windows.RoutedEventHandler(mainAppView.Keyboard.TouchScreenKeyboard._InstanceObject_LostFocus);
            mainAppView.Keyboard.TouchScreenKeyboard._InstanceObject.GotFocus += new System.Windows.RoutedEventHandler(mainAppView.Keyboard.TouchScreenKeyboard._InstanceObject_GotFocus);
        }

        

        /// <summary>
        /// paranoid 
        /// function to retain maximised state
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mainView_Resize(object sender, EventArgs e)
        {
           if (WindowState != FormWindowState.Maximized)
                WindowState = FormWindowState.Maximized;
        }

        private void mainView_Deactivate(object sender, EventArgs e)
        {
           //Activate();
           //BringToFront();
           //Focus();
        }


     /// <summary>
     /// 
     /// </summary>
        private void showStoryBox(object e)
        {
            Button tempButton = (Button)e;
            story = new storyForm(tempButton);
            story.Location = new Point(tempButton.Location.X + (story.Size.Width / 2), tempButton.Location.Y);


            story.Visible = true;
            story.TopMost = true;
            story.Focus();
            isMouseHeld = false;
        }


        /// <summary>
        /// When the user holds the mouse button down on the button
        /// It determines whether the button is a template or a new one
        /// and then either moves or copies it appropriately by starting
        /// the DoDragDrop operation.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MouseHeld(object sender, MouseEventArgs e)
        {
            if (story != null)
            {
                story.Close();
                story = null;
            }
            else
            {
                Button tempButton = (Button)sender;
                isMouseHeld = true;
                currentButton = new Button();

                if (!tempButton.Name.StartsWith("newbutton"))
                {
                    currentButton.Width = tempButton.Width;
                    currentButton.Height = tempButton.Height;
                    currentButton.Location = tempButton.Location;
                    currentButton.Name = "newbutton #" + num;
                    num++;


                    currentButton.MouseDown += new System.Windows.Forms.MouseEventHandler(this.MouseHeld);
                    currentButton.MouseUp += new System.Windows.Forms.MouseEventHandler(this.MouseRelease);
                    currentButton.GiveFeedback += new GiveFeedbackEventHandler(source_GiveFeedback);
                    currentButton.Click += new EventHandler(currentButton_Click);
                }
                else
                {
                    currentButton = tempButton;
                }

                currentButton.MouseMove += new MouseEventHandler(currentButton_MouseMove);
                this.lastMouseDownLocation = new Point(e.X, e.Y);
            }
        }

     /// <summary>
     /// does not even get fired.....
     /// </summary>
     /// <param name="sender"></param>
     /// <param name="e"></param>
        void currentButton_Click(object sender, EventArgs e)
        {
            //Button temp = (Button)sender;
           // if (temp.Name.StartsWith("newbutton"))
           // {
            //    showStoryBox(sender);
           // }
        }


     /// <summary>
     /// Creates a drag drop threshold
     /// </summary>
     /// <param name="sender"></param>
     /// <param name="e"></param>
        void currentButton_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && this.lastMouseDownLocation != null && currentButton != null)
            {
                Point cursorPos = new Point(e.X, e.Y);
                Point dragPoint = (Point)this.lastMouseDownLocation;

                Rectangle dragRect = new Rectangle(dragPoint, SystemInformation.DragSize);
                dragRect.X -= (int)(SystemInformation.DragSize.Width / 2);
                dragRect.Y -= (int)(SystemInformation.DragSize.Height / 2);

                if (dragRect.Contains(cursorPos) == false)
                {
                    currentButton.DoDragDrop(currentButton, DragDropEffects.Copy);
                }
            }
        }

        /// <summary>
        /// resets the potential drag drop parameters
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MouseRelease(object sender, MouseEventArgs e)
        {
            if (currentButton != null)
            {
                Button temp = (Button)sender;
                if (temp.Name.StartsWith("newbutton"))
                {
                    showStoryBox(currentButton);
                    isMouseHeld = false;
                    currentButton = null;
                }
            }
        }

        /// <summary>
        /// Sets the dragged buttons location on the component
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pictureBox1_DragDrop(object sender, DragEventArgs e)
        {
            currentButton.Parent = pictureBox1;
            currentButton.Anchor = AnchorStyles.None;
            currentButton.Location = new System.Drawing.Point(e.X-10, e.Y-10);
            isMouseHeld = false;
        }

        //just a stub to enable drag drop since we don't care about
        //the data format
        private void pictureBox1_DragOver(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Copy;
            #region notused text to image cursor generation
            /*
            if (!e.Data.GetDataPresent(typeof(String)))
            {
                e.Effect = DragDropEffects.None;
                return;
            }

            e.Effect = DragDropEffects.Copy;
            string str = e.Data.GetData(typeof(String)) as String;

            SizeF size;
            Font f = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Bold);
            using (Bitmap tmpBmp = new Bitmap(1, 1))
            using (Graphics g = Graphics.FromImage(tmpBmp))
                size = g.MeasureString(str, f);

            Bitmap bitmap = new Bitmap((int)Math.Ceiling(size.Width),
                (int)Math.Ceiling(size.Height));
            using (Graphics g = Graphics.FromImage(bitmap))
                g.DrawString(str, f, Brushes.Black, 0, 0);

            Cursor.Current = CreateCursor(bitmap, 0, 0);
            bitmap.Dispose();
            f.Dispose();
            */
            #endregion
        }

        private void source_GiveFeedback(object sender, GiveFeedbackEventArgs e)
        {
            // Use customized icons for the drag and drop operation
                e.UseDefaultCursors = false;
                Image img = Image.FromFile(@"C:\pics\1.jpg");
                // Set a customized picture as the cursor icon during the operation
                Cursor.Current = new Cursor(((Bitmap)img).GetHicon());

        }

        private void mainView_MouseMove(object sender, MouseEventArgs e)
        {
        }

    }




 /// <summary>
 /// struct related to custom cursor icons
 /// </summary>
 public struct IconInfo
 {
     public bool fIcon;
     public int xHotspot;
     public int yHotspot;
     public IntPtr hbmMask;
     public IntPtr hbmColor;
 }


}

